package cn.edu.gzgs.service.impl;

import cn.edu.gzgs.dto.EmailListDTO;
import cn.edu.gzgs.entity.EmailMsg;
import cn.edu.gzgs.mapper.EmailMsgMapper;
import cn.edu.gzgs.service.EmailMsgService;
import cn.edu.gzgs.websocket.WebSocketServer;
import cn.edu.gzgs.dto.EmailListDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 邮件消息服务实现类
 */
@Slf4j
@Service
public class EmailMsgServiceImpl implements EmailMsgService {

    @Autowired
    private EmailMsgMapper emailMsgMapper;

    // 与前端保持一致的时间格式
    private static final DateTimeFormatter FRONTEND_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy年M月d日HH:mm:ss");

    @Override
    public List<EmailListDTO> getEmailList(String userId) {
        // 查询该用户的所有邮件，按时间倒序排列
        QueryWrapper<EmailMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accept_id", userId)
                .orderByDesc("time");

        List<EmailMsg> emailMsgs = emailMsgMapper.selectList(queryWrapper);

        // 转换为DTO，并处理时间格式
        return emailMsgs.stream().map(emailMsg -> {
            EmailListDTO dto = new EmailListDTO();
            dto.setId(emailMsg.getId());
            dto.setSenderId(emailMsg.getSenderId());
            dto.setSenderName(emailMsg.getSenderName());
            dto.setAcceptId(emailMsg.getAcceptId());
            dto.setTitle(emailMsg.getTitle());
            dto.setType(emailMsg.getType());
            dto.setContent(emailMsg.getContent());
            dto.setIsRead(emailMsg.getIsRead());
            
            // 将LocalDateTime转换为前端期望的字符串格式
            if (emailMsg.getTime() != null) {
                dto.setTime(emailMsg.getTime().format(FRONTEND_TIME_FORMAT));
            }
            
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public int batchMarkAsRead(List<Long> ids, String userId) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        
        return emailMsgMapper.batchUpdateReadStatus(ids, userId);
    }

    @Override
    public int batchDelete(List<Long> ids, String userId) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }

        // 只删除属于该用户的邮件
        QueryWrapper<EmailMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids)
                .eq("accept_id", userId);

        return emailMsgMapper.delete(queryWrapper);
    }

    @Override
    public boolean sendEmail(EmailMsg emailMsg) {
        try {
            // 设置发送时间
            if (emailMsg.getTime() == null) {
                emailMsg.setTime(LocalDateTime.now());
            }
            
            // 默认未读状态
            if (emailMsg.getIsRead() == null) {
                emailMsg.setIsRead(false);
            }

            // 保存到数据库
            int result = emailMsgMapper.insert(emailMsg);
            
            if (result > 0) {
                // 通过WebSocket实时推送给接收者
                EmailListDTO wsMessage = new EmailListDTO();
                wsMessage.setId(emailMsg.getId());
                wsMessage.setSenderId(emailMsg.getSenderId());
                wsMessage.setSenderName(emailMsg.getSenderName());
                wsMessage.setAcceptId(emailMsg.getAcceptId());
                wsMessage.setTitle(emailMsg.getTitle());
                wsMessage.setType(emailMsg.getType());
                wsMessage.setContent(emailMsg.getContent());
                // 确保时间字段不为null
                if (emailMsg.getTime() != null) {
                    wsMessage.setTime(emailMsg.getTime().format(FRONTEND_TIME_FORMAT));
                } else {
                    wsMessage.setTime(LocalDateTime.now().format(FRONTEND_TIME_FORMAT));
                }
                wsMessage.setIsRead(emailMsg.getIsRead());
                
                log.info("WebSocket推送消息详情: id={}, senderId={}, senderName={}, acceptId={}, title={}, type={}", 
                    wsMessage.getId(), wsMessage.getSenderId(), wsMessage.getSenderName(), 
                    wsMessage.getAcceptId(), wsMessage.getTitle(), wsMessage.getType());
                
                WebSocketServer.sendMessageToUser(emailMsg.getAcceptId(), wsMessage);
                
                log.info("邮件发送成功: {} -> {}", emailMsg.getSenderId(), emailMsg.getAcceptId());
                return true;
            }
            
            return false;
        } catch (Exception e) {
            log.error("发送邮件失败", e);
            return false;
        }
    }
}